<?php
// 本类由系统自动生成，仅供测试用途
class Apiv1_FileuploadController extends Ctrl_Api{
	// 上传文件的信息或者说明
	public function message(){
		$app_message = M('app_message');
		$data["record_id"]=$_GET['recordId'];
        $data["addtime"]=date('Y-m-d H:i:s');
        $res = $app_message->add($data);//将接收到的图片信息存入图片表
        if ($res !== false) {
        	$this->success('上传成功',U('newfile'));
        }else{
        	$this->error('上传失败',U('newfile'));
        }
	}

	//生成唯一字符串
    function createunique($len=4){
        $str=uniqid().randomkeys($len);
        return $str;
    }
    //计算上传文件大小
    public function  fileLeng($strlen,$filesize){
        if($strlen<1024)
        {
            $size=$filesize.'b';
        }
        if(($strlen>=1024)&&($strlen<(1024*1024)))
        {
            $size=round($filesize/1024,1).'kb';
        }
        if(($strlen>=(1024*1024))&&($strlen<(1024*1024*1024)))
        {
            $size=round($filesize/(1024*1024),1).'Mb';
        }
        if($strlen>=(1024*1024*1024))
        {
            $size=round($filesize/(1024*1024*1024),1).'Gb';
        }
        return $size;
    }
    /**********************webuload文件上传结束*******************/
    // 检测图片的宽高,超过标准宽高,生成标准图,保留原图
    // 自动转换字符集 支持数组转换
    /**********************webuload2文件上传开始 修改后的代码*******************/
    public function websavefileAction(){
        $p = $_REQUEST;
        $pEventtype = empty($p['event_type'])?Tool_Fnc::ajaxMsg('事件类型不能为空'):Tool_Fnc::safe_string($p['event_type']);
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {                  //表单提交数据的方式
            exit; // finish preflight CORS requests here
        }
        //mytrace('if------REQUEST_METHOD:'.$_SERVER['REQUEST_METHOD']);
// mytrace($_REQUEST[ 'debug' ]);
        if ( !empty($_REQUEST[ 'debug' ]) ) {                           //$_REQUEST接收表单提交的数据
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {                                          
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
    //mytrace('debug');
        @set_time_limit(5 * 60);
        //判断音频还是视频文件
        $tArr = explode('.',$_FILES['file']['name']);
        if(in_array($tArr[1],array("rm","rmvb","asf","avi","mpeg","wmv","mov","mp4","3gp","dat","mtv","amv","dmv","flv"))){
            $targetDir = APPLICATION_PATH . '/public/upload/media/video/'.date('Y').'/'.date('m').'/'.date('d');
            $uploadDir = APPLICATION_PATH . '/public/upload/media/video/'.date('Y').'/'.date('m').'/'.date('d');
        }else if(in_array($tArr[1],array('acc','ape','ogg','wav','wma','mp3','mid','mod'))){
            $targetDir = APPLICATION_PATH . '/public/upload/media/audio/'.date('Y').'/'.date('m').'/'.date('d');
            $uploadDir = APPLICATION_PATH . '/public/upload/media/audio/'.date('Y').'/'.date('m').'/'.date('d');
        }

        //$targetDir = APPLICATION_PATH . '/public/upload/media/'.date('Y').'/'.date('m').'/'.date('d');         //目标地址
        //$uploadDir = APPLICATION_PATH . '/public/upload/media/'.date('Y').'/'.date('m').'/'.date('d');         //目标地址
    //mytrace('path:'.$targetDir);
        $cleanupTargetDir = true; // Remove old files           //删除旧文件
        $maxFileAge = 5 * 3600; // Temp file age in seconds         //临时文件的时间           
        if (!file_exists($targetDir)) {
            $this->createDir($targetDir);                         //地址是否存在，不存在创建
        }

        // Create target dir
        if (!file_exists($uploadDir)) {                         //地址是否存在，不存在创建
            $this->createdDir($uploadDir);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) { 
            $fileName = $_REQUEST["name"];
            $filesize=$_REQUEST["size"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
            $filesize=$_FILES['file']['size'];
        } else {
            $fileName = uniqid("file_");
            $filesize=0;
        }
        $arr=explode('.',$fileName);
        $file_ext =strtolower(end($arr));
        // $fid=randomkeys(20);
        // $savename=$fid.'.'.$file_ext;//保存文件名--随机取名
        //$fids = empty($recordId) ? $progressId : $recordId ;//防止上传文件的ID值重复
        $savename=substr(md5($fileName),0,20).'.'.$file_ext;
        //mytrace('$savename:'.$savename);

        $filePath = $targetDir . DIRECTORY_SEPARATOR .$fileName;                //DIRECTORY_SEPARATOR目录分割符
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $savename;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {//打开失败
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');      //报错
            }
//mytrace('dswe');
            while (($file = readdir($dir)) !== false) {     //打开成功
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                        continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }
        //mytrace('if1');
        // Open temp file
        if (!$out = @fopen($filePath.'_'.$chunk.'.'.'parttmp',"w")) {//打开失败，报错
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
//mytrace('if2');
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
//mytrace('if3');
        while ($buff = fread($in, 4096)) {  //读写文件
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);
//mytrace('xt');
        rename("{$filePath}_{$chunk}.parttmp","{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
  //          mytrace('done122333'.$done);
            // sleep(1);
        if ( $done ) {              //当文件存在
    //        mytrace("文件存在");
            if (!$out = @fopen($uploadPath,"a+")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
      //      mytrace("文件打开成功");
        //    mytrace("filePath-----chunks------".$filePath.'_'.$chunks.'part');

            if ( flock($out, LOCK_EX) ) {       //锁定文件
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen($filePath.'_'.$index.'.'.'part',"rb")) {
                                //打开失败
          //              mytrace("打开失败");
                        break;
                    }else{
            //            mytrace("打开{$filePath}_{$index}.part成功");
                    }
              //      mytrace("打开路径".auto_charset($uploadPath,'utf-8','gbk'));
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                //    mytrace("写完成");
                    @unlink("{$filePath}_{$index}.part");
                    // sleep(1);                        //关闭文件删除文件
                }

                flock($out, LOCK_UN);                                               //释放锁定
            }
            @fclose($out);                                                          //关闭
        }
        
            //mytrace('***************************插入数据库****************************');
        $tempsavename=explode(".",$savename);
        array_pop($tempsavename);
        $tempsavename=implode(".",$tempsavename);
        $new_file_name = ltrim($tempsavename);
        if(in_array($file_ext,array("rm","rmvb","asf","avi","mpeg","wmv","mov","mp4","3gp","dat","mtv","amv","dmv","flv")))
        {
            if ($_POST['chunk'] + 1 == $_POST['chunks']) {
              //  mytrace('*****************视频合并完成****************************');
                //文件保存目录路径
                //$save_path = C('APP_SAVE_PATH'); //默认为 update.php所在目录
                $save_path = '/upload/media/video/'.date('Y').'/'.date('m').'/'.date('d').'/';
                // $new_file_name = ltrim(strstr($savename,'.',true),'.');
                $file_path = $save_path .$new_file_name. '.' . $file_ext;//文件保存路径：Public/upload/app/1f4aa4e8ef32b8e92fbf0ebd22aec5e0.jpg

                //插入视频表
                
                $tEMMO = new EventmediaModel;
                $tEData = $tEMMO->field('id')->where('event_type = '.$pEventtype)->fRow();
                if(!empty($tEData['id'])){
                    $tData = array(
                        'id' => $tEData['id'],
                        'event_type' => $pEventtype,
                        'video' => $file_path,
                        'video_title' => $fileName,
                        'updated' => time(),
                    );
                    if(!$tEMMO->update($tData)){
                        Tool_Fnc::ajaxMsg('视频插入失败');exit;
                    }
                    Tool_Fnc::ajaxMsg('添加成功',1);exit;
                }
                $tData = array(
                    'event_type' => $pEventtype,
                    'video' => $file_path,
                    'video_title' => $fileName,
                    'created' => time(),
                );
                if(!$tEMMO->insert($tData)){
                    Tool_Fnc::ajaxMsg('视频添加失败');exit;
                }
                Tool_Fnc::ajaxMsg('添加成功',1);exit;
            }else{
                exit;
            }
        }

        else if(in_array($file_ext ,array('acc','ape','ogg','wav','wma','mp3','mid','mod')))
        {
            if ($_POST['chunk'] + 1 == $_POST['chunks']) {
                //mytrace('*****************音频合并完成****************************');
                //文件保存目录路径
                //$save_path = C('APP_SAVE_PATH'); //默认为 update.php所在目录
                $save_path = '/upload/media/audio/'.date('Y').'/'.date('m').'/'.date('d').'/';
                // $new_file_name = ltrim(strstr($savename,'.',true),'.');
                $file_path = $save_path .$new_file_name. '.' . $file_ext;//文件保存路径：Public/upload/app/1f4aa4e8ef32b8e92fbf0ebd22aec5e0.jpg
                //保存文件信息
                $strlen=$filesize;
                $size = $this->fileLeng($strlen,$filesize);//文件大小

                //插入音频表
                $tEMMO = new EventmediaModel;
                $tEData = $tEMMO->field('id')->where('event_type = '.$pEventtype)->fRow();

                if(!empty($tEData['id'])){
                    $tData = array(
                        'id' => $tEData['id'],
                        'event_type' => $pEventtype,
                        'audio' => $file_path,
                        'audio_title' => $fileName,
                        'updated' => time(),
                    );
                    if(!$tEMMO->update($tData)){
                        Tool_Fnc::ajaxMsg('音频添加失败');exit;
                    }
                    Tool_Fnc::ajaxMsg('添加成功',1);exit;
                }
                $tData = array(
                    'event_type' => $pEventtype,
                    'audio' => $file_path,
                    'audio_title' => $fileName,
                    'created' => time(),
                );
                if(!$tEMMO->insert($tData)){
                    Tool_Fnc::ajaxMsg('音频添加失败');exit;
                }
                Tool_Fnc::ajaxMsg('添加成功',1);exit;
                exit;
            }else{
                exit;
            }                                               
        }

        //保存图片
        else if(in_array($file_ext,array('gif','jpeg','jpg','png','bmp')))
        {
            //新文件名
            // $new_file_name = ltrim(strstr($savename,'.',true),'.');
            //mytrace('$new_file_name:'.JSON($new_file_name));

            //文件保存目录路径
            $save_path = ''; //默认为 update.php所在目录
            //文件保存目录URL
            $save_url = ''; //默认为 update.php所在目录

            //mytrace('$savename:'.JSON($savename));
            $file_ext = ltrim(strrchr($savename,'.'),'.');//后缀名
            //mytrace('$file_ext:'.JSON($file_ext));
            //移动文件
            //$file_path = $save_path . "original_".$new_file_name. '.' . $file_ext;
            $file_path = $save_path .$new_file_name. '.' . $file_ext;//文件保存路径：Public/upload/app/1f4aa4e8ef32b8e92fbf0ebd22aec5e0.jpg
            //mytrace('$file_path:'.$file_path);

            //保存文件信息
            $filesize=$_FILES['file']['size'];
            $strlen=$filesize;
            $size = $this->fileLeng($strlen,$filesize);//文件大小

            //$standard_image=C('path').$new_file_name.'.'.$file_ext; //标准图片绝对路径
            //$original_image=C('path')."original_".$new_file_name.'.'.$file_ext; //原图图片绝对路径
            //$judpathsm=C('path')."small_".$new_file_name.'.'.$file_ext; //绝对路径
            import('ORG.Util.Image');
            $image=new Image();
            // 获取图片的大小
            $sizes  =  getimagesize ( $file_path );
            //mytrace('$file_path---$sizes-----'.JSON($sizes));
            $sizeWidth = $sizes[0];
            $sizeHeight = $sizes[1];
            if ($sizeWidth > C('standardImage.width') || $sizeHeight > C('standardImage.height')) {
                // $image->thumb($file_path,$original_image,$file_ext,$sizeWidth,$sizeHeight);
                rename($file_path,$original_image);
                $image->thumb($original_image,$standard_image,"",C('standardImage.width'),C('standardImage.height'));
                if(filesize($original_image)<filesize($standard_image)){
                    copy($original_image,$standard_image);  
                }
            }
            $image->thumb($standard_image,$judpathsm,"",C('smallImage.width'),C('smallImage.height'));
            if(filesize($standard_image)<filesize($judpathsm)){
                copy($standard_image,$judpathsm);   
            }

            //插入app_photo表
            //图片插入数据库之前查看数据库是否已经存在
            //$where['photo_id'] = $data["photo_id"];
            //$res = $app_photo->where($where)->find();
            //if($res){
            //  mytrace('图片已经存在-----'.JSON($res));
            //}
            //mytrace('app_photo---data-----'.JSON($data));
            //mytrace('app_photo-----'.JSON($app_photo->getlastsql()));
        }
        else
            //if(in_array($file_ext,array('doc','docx','xls','xlsx','ppt','pptx')))
        {
            if ($_POST['chunk'] + 1 == $_POST['chunks'] || empty($_POST['chunks'])) {
                //文件保存目录路径
                $save_path = C('APP_SAVE_PATH'); //默认为 update.php所在目录
                // $new_file_name = ltrim(strstr($savename,'.',true),'.');
                $file_path = $save_path .$new_file_name. '.' . $file_ext;//文件保存路径：Public/upload/app/1f4aa4e8ef32b8e92fbf0ebd22aec5e0.jpg
                //保存文件信息
                $filesize=$_POST['size'];
                $strlen=$filesize;
                $size = $this->fileLeng($strlen,$filesize);//文件大小

                $other =M("app_attach");
                $data["attach_id"]=$new_file_name;
                $data["filename"]=$fileName;
                $data["locaddress"]=$file_path;
                $data["record_id"]=$recordId;
                $data["size"]=$size;
                //office文档转化PDF,
                if(in_array(strtolower($fileinfo['extension']),array('doc','docx','xls','xlsx','ppt','pptx')))
                {
                    $document_path=getcwd();//获取当前路径
                    $document_path=str_replace("\\","/",$document_path)."/";
                    $output_dir = $document_path.C('APP_SAVE_PATH').'officepdf/';
                    // $output_dir='./'.C('APP_SAVE_PATH').'officepdf/';
                    $doc_file = $document_path.C('APP_SAVE_PATH').$new_file_name.'.'.$file_ext;
                    $fileid=$new_file_name;
                    $pdf_file =$fileid.".pdf";
                    $output_file = $output_dir . $pdf_file;
                    $doc_file = "file:///" . $doc_file;
                    $output_file = "file:///" . $output_file;
                    $quality=A('Quality');
                    $quality->word2pdf($doc_file,$output_file);
                    $data["officeaddress"]=C('APP_SAVE_PATH').'officepdf/'.$pdf_file;
                }
                $otherflag=$other->add($data);//将接收到的其他信息存入图片表
                mytrace('插入文档数据:'.JSON($data));
                mytrace('$other-----'.JSON($other->getlastsql()));
                exit;
            }else{
                exit;
            }

        }
        mytrace('***************************websavefile----分割线结束***************************************'."\n\r");

    }
	/**
	 * Create directory recursively
	 */
	private function createDir($folder){
		$reval = false;
		if(!file_exists($folder)){
			@umask(0);
			preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
			$base = ($atmp[0][0] == '/') ? '/' : '';
			
			foreach($atmp[1] AS $val) {
				if('' != $val){
					$base .= $val;
					if ('..' == $val || '.' == $val) {
						$base .= '/';
						continue;
					}
				}else{
					continue;
				}

				$base .= '/';

				if(!file_exists($base)){
					if(@mkdir($base, 0777)){
						@chmod($base, 0777);
						$reval = true;
					}
				}
			}
		}else{
			$reval = is_dir($folder);
		}
		
		clearstatcache();
		return $reval;
	}
}

